package com.ruoyi.exam.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.exam.domain.PAnswer;
import com.ruoyi.exam.domain.PQuestion;
import com.ruoyi.exam.domain.PQuestionTypeEntity;
import com.ruoyi.exam.mapper.PAnswerMapper;
import com.ruoyi.exam.mapper.PQuestionMapper;
import com.ruoyi.exam.service.IPQuestionService;
import com.ruoyi.exam.service.PQuestionTypeService;
import com.ruoyi.exam.vo.*;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 试题Service业务层处理
 *
 * @author ruoyi
 * @date 2021-12-31
 */
@Service
public class PQuestionServiceImpl implements IPQuestionService
{
    @Autowired
    private PQuestionMapper pQuestionMapper;

    @Autowired
    private PAnswerMapper pAnswerMapper;

    @Autowired
    private PQuestionTypeService pQuestionTypeService;

    /**
     * 查询试题
     *
     * @param id 试题主键
     * @param type 是否修改
     * @return 试题
     */
    @Override
    public QuestionVo selectPQuestionById(Long id,Boolean type) {

        Map<Integer, PQuestionTypeEntity> dict = new HashMap<>();
        List<PQuestionTypeEntity> pQuestionTypeEntities = pQuestionTypeService.selectAll();
        for (PQuestionTypeEntity pQuestionTypeEntity : pQuestionTypeEntities) {
          dict.put(pQuestionTypeEntity.getId(),pQuestionTypeEntity);
        }

        QuestionVo questionVoB = new QuestionVo();
        PQuestion question = pQuestionMapper.selectPQuestionById(id);
        if(question.getQuType() != null ){ // 判断type 是否B型题 是 将B型题id为parentId 查询全部题目
            PAnswer answer = pAnswerMapper.getQuestionId(question.getId());
            //设置字段
            questionVoB.setQuestionContent(question.getQuContent());
            questionVoB.setAnalysis(question.getAnalysis());
//            questionVoB.setQuestionType(Integer.valueOf(question.getQuType().toString()));
            questionVoB.setQuestionLevel(Integer.valueOf(question.getLevel().toString()));
            questionVoB.setQuestionId(Integer.valueOf(question.getId().toString()));
            questionVoB.setQuGeneral(question.getQuGeneral());
            questionVoB.setQuParentId(question.getQuParentId());
            questionVoB.setCaseExamples(question.getCaseExamples());
            questionVoB.setBankId(Integer.valueOf(question.getQuBankId().toString())); //设置所属题库
            PQuestionTypeEntity pQuestionTypeEntity = dict.get(question.getQuType().intValue());
            String name;
            if(Objects.nonNull(pQuestionTypeEntity)){
               name = pQuestionTypeEntity.getName();
               questionVoB.setQuestionType(pQuestionTypeEntity.getType());
            }else{
              questionVoB.setQuestionType(1);
              name = "未知题目";
            }
            questionVoB.setQuestionTypeName(name);

          if (question.getImage() != null && !Objects.equals(question.getImage(), ""))
                questionVoB.setImages(question.getImage().split(","));
            questionVoB.setCreatePerson(question.getCreatePerson());


            if (answer != null) {
                if (Objects.nonNull(pQuestionTypeEntity) && pQuestionTypeEntity.getType()==1) {
                    String[] allOption = answer.getAllOption().split(",");
                    String[] imgs = null;
                    if(answer.getImages() != null){
                         imgs = answer.getImages().split(",");
                    }

                    QuestionVo.Answer[] qa = new QuestionVo.Answer[allOption.length];
                    for (int i = 0; i < allOption.length; i++) {
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setId(i);
                        answer1.setAnswer(allOption[i]);
                        if(answer.getImages() != null) {
                            if (i <= imgs.length - 1 && !Objects.equals(imgs[i], ""))
                                answer1.setImages(new String[]{imgs[i]});
                        }
                        if (i == Integer.parseInt(answer.getTrueOption())) {
                            if(type == true)
                            {
                                answer1.setIsTrue("true");
                            }
                            answer1.setAnalysis(answer.getAnalysis());
                        }
                        qa[i] = answer1;
                    }
                    questionVoB.setAnswer(qa);


                }else
                 {
                     //多选
                     String[] allOption = answer.getAllOption().split(",");
                     String[] imgs = null;
                     if(answer.getImages() != null){
                         imgs = answer.getImages().split(",");
                     }

                     QuestionVo.Answer[] qa = new QuestionVo.Answer[allOption.length];

                     for (int i = 0; i < allOption.length; i++) {
                         QuestionVo.Answer answer1 = new QuestionVo.Answer();
                         answer1.setId(i);
                         answer1.setAnswer(allOption[i]);
                         answer1.setImages(imgs);
                         //通过判断正确答案中 是否有存在对应的id
                         //通过判断查询答案长度，然后在进行对比 添加对应题目中 放置answer
                         int trueLength = answer.getTrueOption().split(",").length;
                         String[] split = answer.getTrueOption().split(",");

                         for (int j = 0; j < trueLength; j++) {
                             if(i == Integer.parseInt(split[j])){
                                 answer1.setIsTrue("true");
                                 answer1.setAnalysis(answer.getAnalysis());
                             }
                         }

                         qa[i] = answer1;
                     }
                     questionVoB.setAnswer(qa);
                 }
            }
        }
        return questionVoB;
    }

    /**
     * 查询试题列表
     *
     * @param pQuestion 试题
     * @return 试题
     */
    @Override
    public List<PQuestion> selectPQuestionList(PQuestion pQuestion)
    {
        return pQuestionMapper.selectPQuestionList(pQuestion);
    }

    @Override
    public List<QuestionListVo> selectPQuestionListVo(PQuestion pQuestion) {
        return pQuestionMapper.selectPQuestionListVo(pQuestion);
    }

    /**
     * 新增试题
     *
     * @param pQuestion 试题
     * @return 结果
     */
    @Override
    public int insertPQuestion(PQuestion pQuestion)
    {
        pQuestion.setCreateTime(DateUtils.getNowDate());
        return pQuestionMapper.insertPQuestion(pQuestion);
    }

    /**
     * 修改试题
     *
     * @param pQuestion 试题
     * @return 结果
     */
    @Override
    public int updatePQuestion(PQuestion pQuestion)
    {
        pQuestion.setUpdateTime(DateUtils.getNowDate());
        return pQuestionMapper.updatePQuestion(pQuestion);
    }

    /**
     * 批量删除试题
     *
     * @param ids 需要删除的试题主键
     * @return 结果
     */
    @Override
    public int deletePQuestionByIds(Long[] ids)
    {
        pAnswerMapper.deletePAnswerByIds(ids);
        return pQuestionMapper.deletePQuestionByIds(ids);
    }

    /**
     * 删除试题信息
     *
     * @param id 试题主键
     * @return 结果
     */
    @Override
    public int deletePQuestionById(Long id)
    {
        return pQuestionMapper.deletePQuestionById(id);
    }

    @Override
    public int sevePQuestion(QuestionVo questionVo,String userName) {
        PQuestion question = new PQuestion();
        //设置基础字段
        question.setQuType(Long.valueOf(questionVo.getQuestionType()));
//        question.setId(currentQuId);

        question.setCreateBy(userName);
        question.setCreateTime(new Date());
        question.setLevel(Long.valueOf(questionVo.getQuestionLevel()));
        question.setAnalysis(questionVo.getAnalysis());
        question.setQuContent(questionVo.getQuestionContent());
        question.setCreatePerson(questionVo.getCreatePerson());
        question.setCaseExamples(questionVo.getCaseExamples());
        //设置所属题库
        question.setQuBankId(Long.valueOf(questionVo.getBankId()));
        //设置题目插图
        if (questionVo.getImages().length != 0) {
            String QuImages = Arrays.toString(questionVo.getImages());
            question.setImage(QuImages.substring(1, QuImages.length() - 1).replaceAll(" ", ""));
        }

        if(questionVo.getQuestionType() == 4){
            if(questionVo.getQuParentId() != null){
                question.setQuParentId(questionVo.getQuParentId());
                question.setQuGeneral(questionVo.getQuGeneral());
            }else{

                PQuestion toList = pQuestionMapper.getToList();
                if(toList != null){
                    question.setQuParentId(toList.getQuParentId()+1);
                    question.setQuGeneral(questionVo.getQuGeneral());
                }else{
                    question.setQuParentId(1);
                    question.setQuGeneral(questionVo.getQuGeneral());
                }

            }

        }


        int i1 = pQuestionMapper.insertPQuestion(question);
        //设置答案对象
        StringBuffer multipleChoice = new StringBuffer();

        PAnswer answer = new PAnswer();
        StringBuffer imgs = new StringBuffer();
        StringBuffer answers = new StringBuffer();
        for (int i = 0; i < questionVo.getAnswer().length; i++) {
            if (questionVo.getAnswer()[i].getImages() != null && questionVo.getAnswer()[i].getImages().length > 0) {//如果该选项有一张图片信息
                imgs.append(questionVo.getAnswer()[i].getImages()[0]).append(",");
            }
            answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
            //设置对的选项的下标值
            if (questionVo.getQuestionType() == 2) {//多选
                if (questionVo.getAnswer()[i].getIsTrue().equals("true")) multipleChoice.append(i).append(",");
            } else {//单选和判断 都是仅有一个答案
                if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                    answer.setTrueOption(i + "");
                    answer.setAnalysis(questionVo.getAnswer()[i].getAnalysis());
                }
            }
        }
        if (questionVo.getQuestionType() == 2)
            answer.setTrueOption(multipleChoice.toString().substring(0, multipleChoice.toString().length() - 1));
        String handleImgs = imgs.toString();
        String handleAnswers = answers.toString();
        if (handleImgs.length() != 0) handleImgs = handleImgs.substring(0, handleImgs.length() - 1);
        if (handleAnswers.length() != 0) handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);

        //设置答案的图片
        answer.setImages(handleImgs);
        //设置所有的选项
        answer.setAllOption(handleAnswers);
        //ID
        answer.setQuestionId(question.getId());
        pAnswerMapper.insertPAnswer(answer);


        return i1;
    }

    @Override
    public int updatePQuestion(QuestionVo questionVo,String userName) {

        PQuestion question = new PQuestion();
        //设置基础字段
        question.setQuType(Long.valueOf(questionVo.getQuestionType()));
        question.setId(Long.valueOf(questionVo.getQuestionId()));
        question.setUpdateBy(userName);
        question.setUpdateTime(new Date());
        question.setLevel(Long.valueOf(questionVo.getQuestionLevel()));
        question.setAnalysis(questionVo.getAnalysis());
        question.setQuContent(questionVo.getQuestionContent());
        question.setCreatePerson(questionVo.getCreatePerson());
        question.setCaseExamples(questionVo.getCaseExamples());
        //设置所属题库
        question.setQuBankId(Long.valueOf(questionVo.getBankId()));
        //设置题目插图
        if (questionVo.getImages() != null && questionVo.getImages().length != 0) {
            String QuImages = Arrays.toString(questionVo.getImages());
            question.setImage(QuImages.substring(1, QuImages.length() - 1).replaceAll(" ", ""));
        }


        //  question.setSort(questionVo.getSort());
        question.setQuGeneral(questionVo.getQuGeneral());
        question.setQuParentId(questionVo.getQuParentId());
        question.setCaseExamples(questionVo.getCaseExamples());

        //更新
        int i1 = pQuestionMapper.updatePQuestion(question);
        //设置答案对象
        StringBuffer multipleChoice = new StringBuffer();
//        PAnswer answer = new PAnswer();
//        answer.setQuestionId(Long.valueOf(questionVo.getQuestionId()));
        //通过 questionid 查询出来后修改
        PAnswer answer = pAnswerMapper.getQuestionId(Long.valueOf(questionVo.getQuestionId()));

        StringBuffer imgs = new StringBuffer();
        StringBuffer answers = new StringBuffer();
        for (int i = 0; i < questionVo.getAnswer().length; i++) {
            if (questionVo.getAnswer()[i].getImages() != null && questionVo.getAnswer()[i].getImages().length > 0) {//如果该选项有一张图片信息
                imgs.append(questionVo.getAnswer()[i].getImages()[0]).append(",");
            }
            answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
            //设置对的选项的下标值
            if (questionVo.getQuestionType() == 2) {//多选
                if (questionVo.getAnswer()[i].getIsTrue().equals("true")){
                    multipleChoice.append(i).append(",");
                }
            } else {//单选和判断 都是仅有一个答案
                if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                    answer.setTrueOption(i + "");
                    answer.setAnalysis(questionVo.getAnswer()[i].getAnalysis());
                }
            }
        }
        if (questionVo.getQuestionType() == 2){
            answer.setTrueOption(multipleChoice.toString().substring(0, multipleChoice.toString().length() - 1));
        }
        String handleImgs = imgs.toString();
        String handleAnswers = answers.toString();
        if (handleImgs.length() != 0) handleImgs = handleImgs.substring(0, handleImgs.length() - 1);
        if (handleAnswers.length() != 0) handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);

        //设置答案的图片
        answer.setImages(handleImgs);
        //设置所有的选项
        answer.setAllOption(handleAnswers);
        pAnswerMapper.updatePAnswer(answer);




        return  i1;
    }



    @Override
    public List<SQuestionResult> randomQuestionList(StudentQuestionVo studentQuestionVo) {
        return  pQuestionMapper.randomQuestionList(studentQuestionVo);
    }

    @Override
    public List<SQuestionResult> findByBQuestion(StudentQuestionVo studentQuestionVo) {
        return pQuestionMapper.findByBQuestion(studentQuestionVo);
    }

    @Override
    public List<SQuestionResult> selectSQuestionList(StudentQuestionVo studentQuestionVo) {
        return pQuestionMapper.selectSQuestionList(studentQuestionVo);
    }

    @Override
    public List<QuestionVo> selectPQuestionByList(Long id, Boolean type, Boolean is_b) {
        return null;
    }

    @Override
    public List<QuestionVo> findByBQuestionInfo(StudentQuestionVo studentQuestionVo) {
        ArrayList<QuestionVo> objects = new ArrayList<>();
        List<BQuestionResult> byBQuestionInfo = pQuestionMapper.findByBQuestionInfo(studentQuestionVo);
        byBQuestionInfo.forEach(bQuestion ->{
            QuestionVo questionVoB = new QuestionVo();
            //设置字段
            questionVoB.setQuestionContent(bQuestion.getQuContent());
            questionVoB.setAnalysis(bQuestion.getPAnswer().getAnalysis());
            questionVoB.setQuestionId(Integer.valueOf(bQuestion.getId().toString()));
            questionVoB.setQuGeneral(bQuestion.getQuGeneral());

            if (bQuestion.getImage() != null && !Objects.equals(bQuestion.getImage(), ""))
                questionVoB.setImages(bQuestion.getImage().split(","));
            if (bQuestion.getPAnswer() != null) {

                String[] allOption = bQuestion.getPAnswer().getAllOption().split(",");
                String[] imgs = null;
                if (bQuestion.getPAnswer().getImages() != null) {
                    imgs = bQuestion.getPAnswer().getImages().split(",");
                }

                QuestionVo.Answer[] qa = new QuestionVo.Answer[allOption.length];
                for (int i = 0; i < allOption.length; i++) {
                    QuestionVo.Answer answer1 = new QuestionVo.Answer();
                    answer1.setId(i);
                    answer1.setAnswer(allOption[i]);
                    if (bQuestion.getPAnswer().getImages() != null) {
                        if (i <= imgs.length - 1 && !Objects.equals(imgs[i], ""))
                            answer1.setImages(new String[]{imgs[i]});
                    }

                    if (bQuestion.getPAnswer().getTrueOption().contains(i+"")) {
                        answer1.setIsTrue("true");
                        answer1.setAnalysis(bQuestion.getPAnswer().getAnalysis());
                    }
                    qa[i] = answer1;
                }
                questionVoB.setAnswer(qa);
                objects.add(questionVoB);

            }

        });



        return objects;
    }



    @Override
    public AjaxResult getTypes() {


        return null;
    }
}
